package miiteen.sys.config;

import cn.gov.customs.casp.sdk.h4a.sso.passport.PassportFilter;
import cn.gov.customs.casp.sdk.h4a.sso.passport.util.CommonHelper;
import cn.gov.customs.casp.sdk.h4a.sso.passport.util.RSAEncryptor;
import miiteen.sys.cache.LoginInfoCache;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        try {
            RSAEncryptor.genKeyPair();
        } catch (Exception var4) {
            throw new RuntimeException(var4.getMessage());
        }

        try {
            CommonHelper.parsePassPortXml();
        } catch (Exception var3) {
            throw new RuntimeException(var3.getMessage());
        }
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //预检返回成功
        if (request.getMethod().equals("OPTIONS")) {
            chain.doFilter(servletRequest, servletResponse);
            return;
        }
        //登录界面不校验
        if (request.getRequestURL().toString().contains("/login") || request.getRequestURL().toString().contains("/Api/basicNavigation/findByList")) {
            chain.doFilter(servletRequest, servletResponse);


            return;
        }
        String token = request.getHeader("token");
        if (StringUtils.isNotBlank(token) && LoginInfoCache.get(token) != null) {
            chain.doFilter(servletRequest, servletResponse);
            return;
        }
        String loginUrl = getLoginUrl(request);
        response.sendRedirect(loginUrl);
    }

    @Override
    public void destroy() {

    }

    /**
     * 获取登录链接
     *
     * @param request
     * @return
     * @throws UnsupportedEncodingException
     */
    private String getLoginUrl(HttpServletRequest request) throws UnsupportedEncodingException {
        String requestUri = request.getRequestURI();
        String requestUrl = request.getRequestURL().toString();
        if (request.getQueryString() != null) {
            requestUrl = requestUrl + "?" + request.getQueryString();
        }
        String regex = "<>;{};'\"\n\r ";
        String uuid = UUID.randomUUID().toString();
        requestUri = requestUri.replaceAll("[" + regex + "]*", "");
        requestUrl = requestUrl.replaceAll("[" + regex + "]*", "");
        String path = request.getContextPath();
        String basePath = request.getScheme().replaceAll("[" + regex + "]*", "") + "://" + request.getServerName() + ":" + request.getServerPort() + path;
        String fc = "False";
        if (new Integer(PassportFilter.slidingTime) != 0) {
            fc = "True";
        }
        String mode = CommonHelper.urlRoleCheck(requestUri.substring(path.length()));
        String defaultMode = PassportFilter.daMode;
        if (mode != null) {
            defaultMode = mode;
        }
        return PassportFilter.authenticateUrl + "?aid=" + PassportFilter.appId + "&pm=" + defaultMode + "&apk=" + CommonHelper.getUrlPubKey() + "&t=" + PassportFilter.paramT + "&lou=" + URLEncoder.encode(basePath + PassportFilter.logOffCallBackUrl, "utf-8") + "&ip=" + request.getRemoteAddr().replaceAll("[" + regex + "]*", "") + "&fciam=False" + "&iam=" + PassportFilter.idMode + "&ru=" + URLEncoder.encode(basePath + "/login", "utf-8") + "&fc=" + fc + "&sid=" + uuid;
    }

    private String getCookieValue(String name, HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        String cookieValue = null;
        if (cookies == null) {
            return cookieValue;
        }
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(name)) {
                cookieValue = cookie.getValue();
                break;
            }
        }
        return cookieValue;
    }
}
